package com.tsp_tux.demo.Util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 该类用于将文件上传至七牛云并返回外链
 * <p>
 *
 * @author 沈育洋
 */
public class QiNiuPicture {

    /**
     * 该函数用于将文件上传至七牛云
     *
     * @param filename    文件名 String
     * @param uploadBytes 上传字节流 byte[]
     * @return 包含key和hash Map<String,String>
     */
    public static Map<String, String> upload(String filename, byte[] uploadBytes) {
        Map<String, String> map = new HashMap<>();

        //配置七牛云服务器上传凭证
        String accessKey = "OQE1LfVH0vDZaf6piQYu4eMgd7N0ABofQLC_bs-5";
        String secretKey = "xBLjhOyu2phHnAtZ3WCa3sIZyP7IzXGWQiFD6hMR";
        String bucket = "dollysheep2";

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Configuration cfg = new Configuration(Region.region1());
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            Response response = uploadManager.put(uploadBytes, filename, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            map.put("key", putRet.key);
            map.put("hash", putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return map;
    }

    /**
     * 拼接外链
     *
     * @param fileName 文件名 String
     * @return 拼接后的外链 String 若为null则表示出错
     */
    public static String outerChainBuild(String fileName) {
        String domainOfBucket = "http://qwmke879k.hb-bkt.clouddn.com";
        String encodedFileName;
        try {
            encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println("拼接错误");
            return null;
        }
        return String.format("%s/%s", domainOfBucket, encodedFileName);
    }
}
